import {router,addRoutes} from './router'
import { getToken } from './composables/auth'
import { toast, showHeaderFullLoading, hideHeaderFullLoading } from "./composables/util"
import store from './store'



// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  showHeaderFullLoading()
  const token = getToken()
    if(!token && to.path != '/login') {
      toast('请先登录', 'error')
      next('/login')
    }
    let hasNewRoutes = false
    // 如果用户登录了，且store中的user信息不存在，则获取用户信息
    if(token && (!store.state.user || !store.state.user.id)) {
      let res = await store.dispatch('getAdminInfo')
      hasNewRoutes = addRoutes(res.data.menus)
    }
    // 设置页面标题
    const title = (to.meta.title || '功能页面') + '-商城管理后台'
    document.title = title
    hasNewRoutes ? next(to.fullPath) : next() 
})

// 全局后置守卫，将全屏Loading关闭
router.afterEach((to, from) => {
  hideHeaderFullLoading()
})